//==============================================================================
//
//             DMutex - the mutex class in the ofc-library
//
//               Copyright (C) 2011  Dick van Oudheusden
//  
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//==============================================================================
// 
//  $Date: 2008-07-20 14:03:51 $ $Revision: 1.11 $
//
//==============================================================================

#include "ofc/DMutex.h"


#if _INTERFACE_

#include "ofc/config.h"

#if defined(HAVE_LIBPTHREAD)
#define HAVE_DMUTEX
#endif

#ifdef HAVE_DMUTEX
//
// The Mutex class implements methods for using a mutex. It wraps around the
// Objective-Cs mutex.
//
// @example
// XXX
// 

@interface DMutex : DObject
{
@private
  objc_mutex_t  _mutex;    // the mutex
}
#endif
#endif


#ifdef HAVE_DMUTEX


@implementation DMutex


//// Constructors

//
// Initialise a mutex
//
// @return the object
//

- (DMutex *) init
{
  _mutex    = objc_mutex_allocate();
  
  return self;
}


//// Copy related methods

//
// Do a shallow copy of the object (not implemented)
//
// @return the object
//
- shallowCopy
{
  WARNING(DW_METHOD_NOT_IMPL, "shallowCopy");
  
  return [super shallowCopy];
}


//// Deconstructor

//
// Free the object
// 

- free
{
  objc_mutex_deallocate(_mutex);

  [super free];
  
  return self;
}


//// Main methods

//
// Lock the mutex
//
// @return the object
//

- (id) lock
{
  objc_mutex_lock(_mutex);

  return self;
}

//
// Unlock the mutex
//
// @return the object
//

- (id) unlock
{
  objc_mutex_unlock(_mutex);
  
  return self;
}

//
// Try to lock the mutex
//
// @return is the mutex locked ?
//

- (BOOL) try
{
  return (objc_mutex_trylock(_mutex) == 0);
}

@end
#endif

/*===========================================================================*/

